$(function() {
    var orderInfo = JSON.parse(wsCommon.getCookie('orderInfo'));
    console.log(orderInfo);
    var cart3 = {
        initData: function() {

            $.ajax({
    			    url: wsCommon.host + '/api/orders/queryByOrderId',
    			    dataType: wsCommon.jsonType,
      				data: {
      					orderId: orderInfo.orderId
      				},
    			    success: function(res) {
    					if(res.code == 1) {
    						if(res.result) {
                          var orders = res.data.orders;

                          $('[data-role="orderid"]').html(orders.orderId);
                          $('[data-role="ordernum"]').html(orders.itemnum);
                          $('[data-role="money"]').html('¥' + orders.finalAmount);
                          if(orders.shippingId == 2) {
                            $('[data-role="addr"]').html('请您在 ' + orders.shipTime + ' 移步至： ' + orders.shipAddr + ' 取货。届时请向工作人员提供该订单编号或手机号码取单。')
                          } else {
                            $('[data-role="addr"]').html('收货信息：' + orders.shipArea+orders.shipAddr + ' ' +orders.shipName + ' ' +orders.shipTime);
                          }
                          $('[data-role="payment"]').html(orders.paymentName);

                          $('[data-role="checkorder"]').prop('href', './member-orderdetail.html?orderId=' + orders.orderId);

                          if(orders.memo) {
                              $('[data-role="memoCon"]').html(orders.memo);
                          } else {
                              $('[data-role="memoCon"]').html('无');
                          }

                          if(orders.paymentType == 2 || orders.paymentType == 1) {
                              $('[data-role="msg-cont"]').html('订单提交成功，我们将为您送货上门！');
                              $('[data-role="toorder"]').hide();
                              $('[data-role="ordertips"]').hide();
                          } else {
                              var tips = '您的订单已经提交成功，请尽快付款。'
                              if(orders.shippingId == 2) tips += '该订单为上门自提订单。'
                              $('[data-role="msg-cont"]').html(tips);
                              $('[data-role="toorder"]').show();
                              $('[data-role="ordertips"]').show();
                          }

                          cart3.listPayment(orders.shippingId);
                      } else {
                          wsCommon.setCookie('go_back_link', window.location.href);
          	              window.location.href = './passport-login.html';
                      }
                  }
              }
          })
        },
        listPayment: function(shippingId) {
            $.ajax({
                url: wsCommon.host + '/api/payments/getMethodByPlatformTag',
                dataType: wsCommon.jsonType,
                data: {
                    platformTag: 1
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            var data = res.data;

                            var payMethodTpl = '';
                            // var payMethodTpl2 = '';
                            $.each(data, function(index, item) {
                                var aclass = '';
                                // var bclass = '';
                                if (index == 0) {
                                    aclass = '';
                                    // bclass = 'show';
                                }
                                if(shippingId == 2) {
                                  if(item.paymentCategoryId == 3) {
                                    payMethodTpl += '<li>\
                                                         <div class="consignee-item '+aclass+'" datahint="'+item.description+'" data-id="'+item.id+'">\
                                                            <img src="'+item.logoUrl+'">\
                                                             <span title="'+item.paymentMethodName+'" >'+item.paymentMethodName+'</span><b></b>\
                                                         </div>\
                                                        </li>';
                                  }
                                } else {
                                  payMethodTpl += '<li>\
                                                       <div class="consignee-item '+aclass+'" datahint="'+item.description+'" data-id="'+item.id+'">\
                                                          <img src="'+item.logoUrl+'">\
                                                           <span title="'+item.paymentMethodName+'" >'+item.paymentMethodName+'</span><b></b>\
                                                       </div>\
                                                      </li>';
                                }
                            })
                            $('[data-role="payMethod"] .change-payment').html(payMethodTpl);
                            // $('[data-role="payMethod"]').append(payMethodTpl2);
                            $('[data-role="payMethod"]').append('<button type="button" class="btn btn-caution action-confirm-payment" style="margin-left:25px;margin-top:10px;"><span><span>确认支付方式</span></span></button>');
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {
                    // console.log('购物车显示接口返回失败');
                }
            })
        },
        changePayment: function() {
            //更换支付方式弹层
    		$(".action-choose-payment").click(function(){
    			// alert(body.width);
                var payment = $('[data-role="payment"]').html();
                $.each($('.change-payment .consignee-item '), function(index, item) {
                    if($(item).find('span').html() == payment) {
                        $(item).addClass('item-selected');
                    }
                })
    			 $("#pop-choose-payment").show();
    			 $(".mask").show();
    		})
    		$(document).on('click',".action-confirm-payment",function(){
                var id = $('.change-payment .item-selected').attr('data-id');
                // var value = $('.change-payment .item-selected').find('span').val();
                // var type = $('[data-role="payMethod"]').find('input:checked').attr('data-type');
                if(!id) {
                    iosOverlay({
                        text: "请选择支付方式!",
                        duration: 1000
                    });
                } else {
                    $.ajax({
                        url: wsCommon.host + '/api/orders/changePayment',
                        dataType: wsCommon.jsonType,
                        data: {
                            orderId: orderInfo.orderId,
                            payment: id
                        },
                        success: function(res) {
                            if(res.code == 1) {
                                if(res.result) {
                                    $('[data-role="payment"]').html(res.data.paymentName);
                                    orderInfo.paymentName = res.data.paymentName;
                                    orderInfo.payment = id;
                                    orderInfo.paymentType = res.data.paymentType;
                                    wsCommon.setCookie('orderInfo', JSON.stringify(orderInfo));

                                    if(orderInfo.paymentType == 2 || orderInfo.paymentType == 1) {
                                        $('[data-role="msg-cont"]').html('订单提交成功，我们将为您送货上门！');
                                        $('[data-role="toorder"]').hide();
                                        $('[data-role="ordertips"]').hide();
                                    } else {
                                        $('[data-role="msg-cont"]').html('您的订单已经提交成功，请尽快付款。');
                                        $('[data-role="toorder"]').show();
                                        $('[data-role="ordertips"]').show();
                                    }

                                    $("#pop-choose-payment").hide();
                       			    $(".mask").hide();
                                } else {
                                    wsCommon.setCookie('go_back_link', window.location.href);
                                    window.location.href = './passport-login.html';
                                }
                            }
                        },
                        error: function() {
                            // console.log('修改支付方式接口返回失败');
                        }
                    })
                }
    		})
    		$(document).on('click',"#pop-close-payment",function(){
    		     $("#pop-choose-payment").hide();
    			 $(".mask").hide();
    		})

    		//支付方式
    		$(document).on('click', ".change-payment .consignee-item",function(){
    			 var $this = $(this);
    			  var tempN = $(".change-payment .consignee-item").index($this);
    			 if($this.hasClass("item-selected")){
    				   return false;
    				 }else{
    					 $(".change-payment .consignee-item").removeClass("item-selected");
    					 $this.addClass("item-selected");
    					 $(".payment-tip").hide();
    					 $(".payment-tip").eq(tempN).show();
    				  }
    		})
        },
        toPay: function() {
            $('[data-role="checkOrder"]').on('click', function() {
                window.location.href = '/member-orderdetail.html?orderId=' + orderInfo.orderId;
            })
            $(document).on('click', '#pay-tips-close', function() {
                window.location.reload();
            })

            $(document).on('click', '[data-role="toorder"]', function() {
                var $this= $(this);
                if($this.hasClass('is-disabled')) return;
                $this.addClass('is-disabled');

                cart3.newLink('/paying.html?id='+orderInfo.orderId)

                $('#pay-tips').show();
                $(".mask").show();

            })
        },
        newLink: function(url){
            var link = document.createElement('a');
            link.href = url;
            link.target = '_blank';
            link.className = 'u-hide';
            document.body.appendChild(link);
            link.click();
            $(link).remove();
            link = null;
        },
        checkorder: function(id) {
            $.ajax({
                url: wsCommon.host + '/api/orders/queryByOrderId',
                dataType: wsCommon.jsonType,
                data: {
                    orderId:id,
                    isShowDetail: false,
                    isShowLog: false,
                    isShowCoupon: false
                },
                success: function(res) {
                    if(res.code == 1) {
                        if(res.result) {
                            if(res.data.orders.payStatus == 1) {
                                window.location.href = wsCommon.host +'/pay-success.html?orderId=' + id;
                            }
                        } else {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                        }
                    }
                },
                error: function() {}
            })
        },
        back: function() {
            wsCommon.setCookie('isBackCart2', true);
        },
        init: function() {
            this.checkorder(orderInfo.orderId);
            this.changePayment();
            this.initData();
            this.toPay();
            this.back();
        }
    }

    cart3.init();
})
